<!-- 车辆列表 -->
<template>
  <div
    ref="contentData"
    class="dashboard-container  customer-list-box"
  >
    <div class="app-container ">
      <el-card
        class="search-card-box"
        shadow="never"
      >
        <el-form
          ref="driverSearchFormData"
          :model="driverSearchFormData"
          label-width="80px"
        >
          <el-row :gutter="60">
            <el-col :span="8">
              <el-form-item
                label="车辆类型:"
                style="margin-bottom: 20px"
                label-width="80px"
              >
                <el-select
                  v-model="driverSearchFormData.vehicleType"
                  style="width: 100%"
                  class="filter-item size"
                  size="small"
                  filterable
                  clearable
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in vehicleType"
                    :key="item.id"
                    :label="item.truckTypeName"
                    :value="item.id"
                    class="size"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                label="车辆号码:"
                style="margin-bottom: 20px"
                label-width="80px"
              >
                <el-input v-model="driverSearchFormData.licensePlate" placeholder="请输入车辆号码" />
              </el-form-item>
            </el-col>
            <el-col :span="8" style="padding-left:50px">
              <el-button type="warning" @click="handleFilter('查询')"
              >搜索
              </el-button
              >
              <el-button
                plain
                class="reset-btn"
                @click="resetForm"
              >重置
              </el-button
              >
            </el-col>
          </el-row>
        </el-form>
      </el-card>
      <TabChange
        :default-active-index="2"
        :setting-list="settingList"
        @tabChange="tabChange"
      ></TabChange>
      <div
        v-loading="listLoading"
        :class="{ 'loading-box': listLoading }"
        element-loading-text="加载中"
        style="margin-top: 20px"
      >
        <el-card shadow="never" class="table-card-box">
          <el-button
            type="warning"
            style="margin-bottom:20px"
            @click="handleAdd()"
          >新增车辆
          </el-button
          >
          <el-table
            ref="multipleTable"
            :data="dataList"
            fit
            style="width: 100%"
            stripe
            :header-cell-style="{ background: 'rgba(250,252,255,1)' }"
          >
            <div
              v-show="
                (!dataList || dataList.length <= 0) &&
                  !listLoading &&
                  !searchkey
              "
              slot="empty"
            >
              <img
                src="@/icons/pic-kong@2x.png"
                alt="img"
                style="margin-top: 20px;width: 14%;height: 14%;"
              />
              <p
                style="
          margin-top: -20px;
          padding-bottom: 0px;
          "
              >
                这里空空如也
              </p>
            </div>
            <el-card
              v-show="
                (!dataList || dataList.length <= 0) && !listLoading && searchkey
              "
              slot="empty"
              class="table-empty-box"
              shadow="never"
            >
              <empty></empty>
            </el-card>
            <el-table-column align="left" type="index" label="序号" width="60">
              <template slot-scope="scope">
                <span>{{
                    scope.$index +
                    (driverSearchFormData.page - 1) *
                    driverSearchFormData.pageSize +
                    1
                  }}</span>
              </template>
            </el-table-column>
            <el-table-column
              align="left"
              label="车辆号码"
              min-width="130"
              prop="licensePlate"
            >
            </el-table-column>
            <el-table-column
              align="left"
              label="车辆类型"
              min-width="130"
              prop="truckTypeName"
            >
            </el-table-column>
            <el-table-column
              align="left"
              label="司机数量"
              min-width="130"
              prop="driverNum"
            >
            </el-table-column>
            <el-table-column
              align="left"
              label="车辆状态"
              min-width="130"
              prop="status"
            >
              <template slot-scope="scope">
                <span v-if="scope.row.workStatus === 0"><i class="red-circle"></i>停用</span>
                <span v-else-if="scope.row.workStatus === 1"><i class="green-circle"></i>可用</span>
              </template>
            </el-table-column>
            <el-table-column
              align="left"
              label="GPS设备ID"
              min-width="130"
              prop="deviceGpsId"
            >
            </el-table-column>
            <el-table-column
              align="left"
              label="实载重量"
              min-width="130"
              prop="allowableLoad"
            >
            </el-table-column>
            <el-table-column
              align="left"
              label="实载体积（方）"
              min-width="130"
              prop="allowableVolume"
            >
            </el-table-column>
            <el-table-column
              align="center"
              fixed="right"
              label="操作"
              width="190"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope">
                <el-link
                  type="primary"
                  :underline="false"
                  @click="handleVehicleDetail(scope.row.id, scope.row.truckTypeId)"
                >查看详情
                </el-link>
                <span class="line"></span>
                <el-link
                  type="primary"
                  :underline="false"
                  @click="handleEnableVehicle(scope.row.id,scope.row.workStatus)"
                >
                  <span v-if="scope.row.workStatus === 0">启用</span>
                  <span v-else-if="scope.row.workStatus === 1" style="color: red">停用</span>

                </el-link>
                <span class="line"></span>
                <el-link
                  type="primary"
                  :underline="false"
                  @click="handleConfigDriver(scope.row.id)"
                >配置司机
                </el-link>
              </template>
            </el-table-column>
          </el-table>
          <!-- 新增车辆 -->
          <vehicle-add
            ref="addVehicle"
            class="add-form-dialog"
            @resetForm="resetForm"
            :title-info="titleInfo"
            :form-base="formData"
            :agency-options="agencyOptions"
            :vehicle-type="vehicleType"
          />
          <!-- end -->

          <!-- 分页 -->
          <div v-show="dataList && dataList.length > 0" class="pagination">
            <div class="pages">
              <el-pagination
                :current-page="Number(driverSearchFormData.page)"
                :total="Number(total)"
                :page-size="Number(driverSearchFormData.pageSize)"
                :page-sizes="[10, 20, 30, 50]"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </div>
        </el-card>
      </div>
      <!--    配置司机-->
      <el-dialog
        title="配置司机"
        :visible.sync="dialogVisible"
        width="50%"
        :before-close="handleClose"
      >
        <el-card>
          <el-form ref="vehicleDetailList" :model="vehicleDetailList" label-width="100px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="车牌号">
                  <label>{{ vehicleDetailList.licensePlate }}</label>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="车型">
                  <label>{{ vehicleDetailList.truckTypeName }}</label>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="车辆状态">
                  <label>
                    <span v-if="vehicleDetailList.workStatus === 0">停用</span>
                    <span v-else-if="vehicleDetailList.workStatus === 1">可用</span>
                  </label>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="实载重量">
                  <label>{{ vehicleDetailList.allowableLoad }}</label>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="实载体积">
                  <label>{{ vehicleDetailList.allowableVolume }}</label>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
        <el-form>
          <el-form-item label="配置司机" prop="id">
            <el-select placeholder="请选择" v-model="driverListChoice.id" @selection-change="handleSelectionChange">
              <el-option
                v-for="item in driverListChoice"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <el-table
          ref="multipleTable"
          :data="driverList"
          fit
          style="width: 100%"
          stripe
          :header-cell-style="{ background: 'rgba(250,252,255,1)' }"
        >
          <div
            v-show="
                (!driverList || driverList.length <= 0) &&
                  !listLoading &&
                  !searchkey
              "
            slot="empty"
          >
            <img
              src="@/icons/pic-kong@2x.png"
              alt="img"
              style="margin-top: 20px;width: 14%;height: 14%;"
            />
            <p
              style="
              margin-top: -20px;
              padding-bottom: 0px;
              "
            >
              这里空空如也
            </p>
          </div>
          <el-card
            v-show="
                (!driverList || driverList.length <= 0) && !listLoading && searchkey
              "
            slot="empty"
            class="table-empty-box"
            shadow="never"
          >
            <empty></empty>
          </el-card>
          <el-table-column align="left" type="index" label="序号" width="60">
            <template>
              <span>{{ index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column align="left" label="司机姓名" min-width="80" prop="name"></el-table-column>
          <el-table-column
            align="center"
            fixed="right"
            label="操作"
            width="120"
            class-name="small-padding fixed-width"
          >
            <el-col width="100%" slot-scope="scope">
              <!-- 调用的编辑方法 -->
              <el-button
                @click="handleEditDriver(scope.row)"
                class="customer-add-btn"
                style="color:#419EFF;border: none;padding: 0; margin: 0;background-color:transparent;"
              >编辑
              </el-button>
              <span class="line"></span>
              <el-button
                @click="handleDelDriver(scope.row.id)"
                class="customer-add-btn"
                style="border: none;padding: 0; margin: 0;background-color:transparent;color:#F56C6C;"
              >删除
              </el-button>
            </el-col>
          </el-table-column>
        </el-table>
        <span slot="footer" class="dialog-footer" style="text-align: center;">
          <el-button type="danger" @click="submitDriverConfig">确 定</el-button>
          <el-button @click="dialogVisible = false">取 消</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  addVehicleBinding,
  getTruckPage,
  getUnbindingDrivers,
  getVehicleDetail,
  getVehicleStatic,
  getVehicleWorking
} from '@/api/vehicle'
import VehicleAdd from '@/views/transit/components/vehicle-add.vue'
import TabChange from '@/components/TabChange'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import form from 'element-ui/packages/form'

export default {
  name: 'Courses',
  computed: {
    form() {
      return form
    }
  },
  components: { VehicleAdd, TabChange },
  data() {
    return {
      index: 0,
      driverListChoice: [],
      driverList: [],
      vehicleDetailList: {},
      settingList: [
        {
          value: 2,
          label: '全部',
          num: 0
        },
        {
          value: 1,
          label: '可用',
          num: 0
        },
        {
          value: 0,
          label: '停用',
          num: 0
        }
      ],
      vehicleType: [
        {
          id: '1',
          truckTypeName: '4.2米高栏'
        },
        {
          id: '2',
          truckTypeName: '4.2米厢式货车'
        },
        {
          id: '3',
          truckTypeName: '6.8米高栏'
        },
        {
          id: '4',
          truckTypeName: '6.8米厢式货车'
        }
      ],
      searchkey: '',
      total: null,
      titleInfo: {},
      formData: {},
      agencyOptions: [],
      dataList: [],
      selectTrunkId: '',
      driverSearchFormData: {
        page: 1,
        pageSize: 10,
        id: '',
        truckTypeId: '' // 车型id
      },
      listLoading: false,
      dialogVisible: false,
      formBase: {
        dispatchMethod: 2,
        dispatchTime: ''
      }
    }
  },
  created() {
    const _this = this
    this.getDriverList()
    this.getVehicleStatic()
    // 键盘enter操作
    document.onkeydown = function(e) {
      const key = window.event.keyCode
      if (key === 13) {
        _this.handleFilter(this.driverSearchFormData)
      }
    }
  },
  mounted() {
    // this.getDriverList()
    // this.getVehicleDetailList()
  },
  methods: {
    submitDriverConfig(id) {
      addVehicleBinding({ 'truckId': this.selectTrunkId, 'driverIds': [this.driverList.id] })
        .then(res => {
          console.log('保存成功', res)
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: '保存成功'
            })
            this.getVehicleDetailList(this.selectTrunkId)
          } else {
            this.$message({
              type: 'error',
              message: res.msg
            })
          }
        })
        .catch(err => {
          this.$message({
            type: 'error',
            message: err.msg
          })
        })
      // this.dialogVisible = false
    },
    // 选中的司机列表渲染
    handleSelectionChange(selection) {
      getUnbindingDrivers(selection)
        .then(res => {
          this.driverListChoice = res.data
        })
      // this.driverListChoice = selection
    },

    // 获取未绑定司机的车辆
    async getUnbindDriversList() {
      const res = await getUnbindingDrivers()
      this.driverListChoice = res.data
    },
    // 获取车辆详情
    async getVehicleDetailList(id) {
      const res = await getVehicleDetail(id)
      this.vehicleDetailList = res.data
    },
    handleDelDriver() {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 获取统计数据
    async getVehicleStatic() {
      const { data: res } = await getVehicleStatic()
      // console.log(res)
      this.settingList[1].num = res[1] || 0
      this.settingList[2].num = res[0] || 0
      this.settingList[0].num =
        Number(this.settingList[1].num) +
        Number(this.settingList[2].num)
    },
    // 状态变更
    tabChange(activeIndex) {
      // 根据 activeIndex 找到对应的状态值
      if (activeIndex !== 2) {
        const statusValue = this.settingList.find(item => item.value === activeIndex).value
        // console.log(statusValue)
        this.driverSearchFormData.workStatus = statusValue
        // console.log(this.driverSearchFormData)
        this.driverSearchFormData.page = 1
      } else {
        this.driverSearchFormData.workStatus = null
        this.driverSearchFormData.page = 1
      }

      this.getDriverList()
    },
    async getDriverList() {
      this.listLoading = true
      const params = { ...this.driverSearchFormData }
      const { data: res } = await getTruckPage(params)
      this.listLoading = false
      // 获取数据给dataList
      this.dataList = res.items
      // 获取总条数
      this.total = res.counts
    },
    // 搜索信息
    handleFilter() {
      this.driverSearchFormData.page = 1
      this.getDriverList(this.driverSearchFormData)
      this.searchkey = true
    },
    // 每页显示信息条数
    handleSizeChange(val) {
      this.driverSearchFormData.pageSize = val
      if (this.driverSearchFormData.page === 1) {
        this.getDriverList(this.driverSearchFormData)
      }
    },
    // 进入某一页
    handleCurrentChange(val) {
      this.driverSearchFormData.page = val
      this.getDriverList()
    },
    // 重置
    resetForm(driverSearchFormData) {
      // 之所以注释掉是因为这里必须配合prop对表单进行赋值，但后端有的字段不支持空串
      // this.$refs[driverSearchFormData].resetFields()
      this.driverSearchFormData = {
        page: 1,
        pageSize: 10,
        status: this.driverSearchFormData.status
      }
      this.searchkey = false
      this.getDriverList()
    },
    // 打开弹窗
    handleDispatch() {
      this.dialogVisible = true
    },
    // 关闭弹窗
    handleClose() {
      this.dialogVisible = false
    },
    // 车型详情
    handleVehicleDetail(id, truckTypeId) {
      this.$router.push({
        path: '/transit/vehicle-detail',
        query: { id: id, truckTypeId: truckTypeId }
      })
    },
    // 新增车辆
    async handleAdd() {
      this.titleInfo.text = '新增车辆'
      this.formData = {}
      this.$refs.addVehicle.dialogFormV()
    },
    handleConfigDriver(id) {
      const h = this.$createElement
      this.$msgbox({
        title: '车辆配置',
        message: h('p', null, [
          h('p', null, '配置司机需满足以下条件 '),
          h('i', { style: 'color: #333' }, '1 车辆信息已完善'),
          h('i', { style: 'color: #333', paddingLeft: '20px' }, '2 车辆无未完成运输任务')
        ]),
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            // 车辆信息已完善
            getVehicleDetail(id)
              .then(res => {
                if (res.data.status !== 1) {
                  this.$message({
                    message: '请先完善车辆信息',
                    type: 'warning'
                  })
                  return
                }
                this.dialogVisible = true
                this.selectTrunkId = id
                this.getVehicleDetailList(id)
                this.getUnbindDriversList()
                this.handleSelectionChange(id)
                done()
              })
          } else {
            this.dialogVisible = false
            done()
          }
        }
      })
    },
    handleEnableVehicle(id, workStatus) {
      if (workStatus === 0) {
        const h = this.$createElement
        this.$msgbox({
          title: '确定要启用吗?',
          message: h('p', null, [
            h('p', null, '车辆启用需满足以下条件 '),
            h('i', { style: 'color: #333' }, '① 车辆信息已完善'),
            h('i', { style: 'color: #333', paddingLeft: '20px' }, '② 绑定司机>=2,且有排班')
          ]),
          showCancelButton: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              // 启用车辆
              getVehicleWorking(id)
                .then(res => {
                  this.$message({
                    message: '车辆启用成功',
                    type: 'success'
                  })
                  this.driverSearchFormData.workStatus === 1
                  this.getDriverList()
                  done()
                })
                .catch(e => {
                  this.$message({
                    message: `车辆启用失败,原因是${e.message}}`,
                    type: 'warning'
                  })
                })
            }
          }
        })
      } else {
        const h = this.$createElement
        this.$msgbox({
          title: '确定要停用吗?',
          message: h('p', null, [
            h('p', null, '车辆停用需满足以下条件'),
            h('i', { style: 'color: #333' }, '① 车辆信息已完善'),
            h('i', { style: 'color: #333', paddingLeft: '20px' }, '② 绑定司机>=2,且有排班'),
            h('p', { style: 'color: #333;backgroundColor:#FFF3EF ' }, '注:停用后司机将自动解除绑定')
          ]),
          showCancelButton: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              // 启用车辆
              getVehicleWorking(id)
                .then(res => {
                  this.$message({
                    message: '车辆停用成功',
                    type: 'success'
                  })
                })
                .catch(e => {
                  this.$message({
                    message: `车辆停用失败,原因是${e.message}}`,
                    type: 'warning'
                  })
                })
            }
          }
        })
      }
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .el-dialog__footer {
  text-align: center;
}

.alert {
  margin: 10px 0px;
}

.pagination {
  margin-top: 10px;
}

.vehicle ::v-deep .el-table td,
.el-table th {
  padding: 12px 0;
  min-width: 0;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  text-overflow: ellipsis;
  vertical-align: middle;
  position: relative;
  text-align: left;
  overflow: hidden;
}

.vehicle {
  ::v-deep .el-dialog__title {
    width: 73px;
    height: 25px;
    font-size: 18px;
    font-family: PingFangSC, PingFangSC-Regular;
    font-weight: 400;
    text-align: left;
    color: #20232a;
    line-height: 25px;
    letter-spacing: 0px;
  }

  ::v-deep .el-dialog__body {
    text-align: center;
    padding: 20px 20px 0px 20px;
  }

  .warn-img {
    width: 40px;
  }

  p {
    height: 24px;
    font-size: 16px;
    font-family: PingFangSC, PingFangSC-Regular;
    font-weight: 400;
    color: #818693;
    line-height: 24px;
  }
}

// 下拉框
::v-deep .el-select {
  width: 100%;
}
</style>

<style>
.startconfirm {
  width: 481px;

}

.startconfirm .el-message-box__header {
  padding-bottom: 4px;
}

.startconfirm .el-message-box__container {
  margin-bottom: 15px;
}

.confirm .el-message-box__status.el-icon-warning {
  left: 70px;
}

.confirm.el-message-box__title {
  font-size: 16px;
}

.confirm .el-message-box__message p {
  color: #F92D2D;
  margin-top: 5px;
}

.confirm .el-message-box__btns {
  text-align: center;
  margin-top: 10px;
}

.line {
  display: inline-block;
  width: 1px;
  height: 12px;
  background: #E4E7ED;
  margin: 0 4px;
  align-items: baseline;
  margin-top: 8px;
}

.reset-btn {
  height: 40px !important;
}

.filter-item.size .el-input__inner {
  height: 40px !important;
  font-size: 14px !important;
}

.dialog-footer {
  text-align: center;
}

::v-deep .el-form-item__label {
  text-align: left !important;
}

label {
  text-align: left !important;
}
.red-circle{
  margin-right: 4px;
  display: inline-block;
  width: 8px;
  height: 8px;
  background: #F92D2D;
  border-radius: 50%;
}
.green-circle{
  margin-right: 4px;
  display: inline-block;
  width: 8px;
  height: 8px;
  background: #00C853;
  border-radius: 50%;
}
</style>
